<?php

/**
 * Laravel专用验证中间件
 *
 * @noinspection PhpUndefinedClassInspection
 * @noinspection PhpUndefinedNamespaceInspection
 * @noinspection PhpUndefinedFunctionInspection
 * @noinspection PhpUnhandledExceptionInspection
 */

namespace Itwmw\Attributes\Validate\Middlewares\Laravel;

use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AttributeValidatorMiddleware
{
    public function handle(Request $request, \Closure $next): Response
    {
        $actionName = $request->route()->getActionName();
        if (!strpos($actionName, '@')) {
            $controller = $actionName;
            if (!class_exists($controller)) {
                return $next($request);
            }
            $method = '__invoke';
        } else {
            [$controller, $method] = explode('@', $actionName);
        }

        $result = validate_method($controller, $method, $request->all(), $method);
        foreach ($result as $value) {
            app()->scoped($value::class, function () use ($value) {
                return $value;
            });
        }
        return $next($request);
    }
}
